package com.elm_springboot_s.controller;

import com.elm_springboot_s.pojo.User;
import com.elm_springboot_s.pojo.RespondMessage;
import com.elm_springboot_s.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Api(tags = "用户相关接口")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public RespondMessage<String> login(String userName, String password) {
        try {
            String token = userService.login(userName, password);
            if (token != null) {
                return RespondMessage.success(token);
            } else {
                return RespondMessage.error("用户名或密码错误");
            }
        } catch (Exception e) {
            return RespondMessage.error("登录失败：" + e.getMessage());
        }
    }

    @GetMapping("/getUserByName")
    @ApiOperation("根据用户名查询用户信息")
    public RespondMessage<User> getUserByName(String userName) {
        try {
            User user = userService.getUserByName(userName);
            if (user != null) {
                // 出于安全考虑，清除密码信息
                user.setPassword(null);
                return RespondMessage.success(user);
            } else {
                return RespondMessage.error("用户不存在");
            }
        } catch (Exception e) {
            return RespondMessage.error("查询用户失败：" + e.getMessage());
        }
    }

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public RespondMessage<Integer> register(String userName, String password, Integer userSex) {
        try {
            // 先检查用户名是否已存在
            User existingUser = userService.getUserByName(userName);
            if (existingUser != null) {
                return RespondMessage.error("用户名已存在");
            }
            
            int result = userService.saveUser(userName, password, userSex);
            return RespondMessage.success(result);
        } catch (Exception e) {
            return RespondMessage.error("注册失败：" + e.getMessage());
        }
    }
}